# ***********下载huggingface 模型
import requests
import os
 
def download_file(url, dest_folder, file_name):
    """
    下载文件并保存到指定的文件夹中。
    """
    response = requests.get(url, allow_redirects=True)
    if response.status_code == 200:
        with open(os.path.join(dest_folder, file_name), 'wb') as file:
            file.write(response.content)
    else:
        print(f"Failed to download {file_name}. Status code: {response.status_code}")
 
def download_model_files(model_name):
    """
    根据模型名称下载模型文件。
    """
    # 文件列表
    files_to_download = [
        "config.json",
        "pytorch_model.bin",
        "tokenizer_config.json",
        "vocab.json",
        "source.spm",
        "target.spm"  # 如果模型不使用SentencePiece，这两个文件可能不需要
    ]
 
    # 创建模型文件夹
    model_folder = model_name.split('/')[-1]  # 从模型名称中获取文件夹名称
    if not os.path.exists(model_folder):
        os.makedirs(model_folder)
 
    # 构建下载链接并下载文件
    # base_url = f"https://huggingface.co/{model_name}/resolve/main/"
    base_url = f"https://hf-mirror.com/{model_name}/resolve/main/"
    for file_name in files_to_download:
        download_url = base_url + file_name
        print(f"Downloading {file_name}...")
        download_file(download_url, model_folder, file_name)
 
# # 示例使用
model_name = "Salesforce/blip-image-captioning-large"
download_model_files(model_name)